package conn

import (
	"io"
	"net/http"
	"net/url"

	"engine/log"
)

type HttpClient interface {
	DoRequest(string, string, map[string]string) (string, error)
}

func NewHttpConn(host string) *HttpConn {
	return &HttpConn{url: "http://" + host}
}

type HttpConn struct {
	url string
}

const (
	ReqGet  = "GET"
	ReqPost = "POST"
)

func (c *HttpConn) DoRequest(reqKind string, router string, params map[string]string) (string, error) {
	conn := &http.Client{}
	urlStr := c.url + router
	if params != nil {
		urlObj, _ := url.Parse(urlStr)
		query := urlObj.Query()
		for key, value := range params {
			query.Set(key, value)
		}
		urlObj.RawQuery = query.Encode()
		urlStr = urlObj.String()
	}

	var req *http.Request
	var err error
	req, err = http.NewRequest(reqKind, urlStr, nil)
	if err != nil {
		log.GetLogger().Error(err.Error()).Println()
		return "", err
	}

	resp, err := conn.Do(req)
	if err != nil {
		log.GetLogger().Error(err.Error()).Println()
		return "", err
	}
	defer resp.Body.Close()

	respBody, err := io.ReadAll(resp.Body)
	if err != nil {
		log.GetLogger().Fatal(err.Error()).Println()
	}

	// log_service.InfoPrintf("%s -> Response:%v", urlStr, string(respBody))
	return string(respBody), nil
}
